package com.itlaobing.config;


import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.EnumSet;
import java.util.Enumeration;

public class ConfigurationServlet implements Servlet {

    private ServletConfig config;

    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        // 通过 ServletConfig 实例来获取 指定的 初始化参数 的 值
        String cn = config.getInitParameter( "charsetName" ); // getInitParameter方法的实参是 初始化参数的名称
        String fo = config.getInitParameter( "force" );
        // 通过 Charset 来检查初始化参数指定的编码是否是可用的
        if( Charset.isSupported( cn ) && Boolean.parseBoolean( fo ) ) {
            // 设置编码
            request.setCharacterEncoding( cn );
            response.setCharacterEncoding( cn );
        } else {
            // 设置编码
            request.setCharacterEncoding( "UTF-8" );
            request.setCharacterEncoding( "UTF-8" );
        }

        // 设置响应的MIME类型
        response.setContentType( "text/html;charset=UTF-8" );

        // 获得字符打印流
        PrintWriter out = response.getWriter();

        Enumeration<String> paramNames = config.getInitParameterNames();
        while( paramNames.hasMoreElements() ) {
            String initParamName = paramNames.nextElement(); // 得到 初始化参数名称
            String initParamValue = config.getInitParameter( initParamName ); // 根据 初始化参数名称 获取 初始化参数值
            out.println("<h3>" + initParamName + " : " + initParamValue + "</h3>");
        }

    }

    @Override
    public void destroy() {

    }

    @Override
    public ServletConfig getServletConfig() {
        return this.config;
    }

    @Override
    public String getServletInfo() {
        return config.getServletName();
    }

}
